﻿using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace QA.TFS.Utils
{
    /// <summary>
    /// Helper para reemplazar la referencia de un parametro de contexto por su valor dentro de una cadena o expresion regular
    /// </summary>
    public class ContextParameterHelper
    {

        public static string replaceContextParameters(WebTestContext context, string content)
        {
            if (!string.IsNullOrWhiteSpace(content))
            {
                if (content.Contains("{{"))
                {
                    Regex extractor;
                    string _Regex = @"\{\{([a-zA-Z.]*)\}\}";
                    extractor = new Regex(_Regex);
                    MatchCollection matches = extractor.Matches(content);
                    if (matches.Count > 0)
                    {
                        foreach (Match item in matches)
                            if (context.ContainsKey(item.Groups[1].Value))
                                content = content.Replace(string.Format("{0}", item.Groups[0].Value), context[item.Groups[1].Value].ToString());
                    }
                }
                else
                {
                    if (context.ContainsKey(content) && !string.IsNullOrEmpty(context[content].ToString()))
                        content = context[content].ToString();
                }
            }
            else
                content = string.Empty;

            return content;

            //string result = "";
            //Regex regExStatement = new Regex(@"(\w*)([\{]{2}([a-zA-Z]*)[\}]{2})+[\,]?");
            //try
            //{
            //    result = regExStatement.Replace(source, delegate(Match match)
            //    {
            //        if (match.Groups.Count == 4)
            //            if (context.ContainsKey(match.Value))
            //                return context[match.Value].ToString();
            //        return match.Value;
            //    });
            //    return result;
            //}
            //catch (Exception e)
            //{
            //    throw e;
            //}

        }

    }
}
